package io.kiki.sba.registry.common.model.store;


import io.kiki.sba.registry.cache.Sizer;
import io.kiki.sba.registry.common.model.PublishSource;
import io.kiki.sba.registry.common.model.ServerData;
import io.kiki.sba.registry.util.StringUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Setter
@Getter
public final class SubPublisher implements Serializable, Sizer {
    private final String registerId;
    private final String cell;
    private final String clientId;
    private final String srcAddressString;
    private final List<ServerData> serverDataList;
    private final long registerTimestamp;
    private final long version;
    private final PublishSource publishSource;

    public SubPublisher(String registerId, String cell, List<ServerData> serverDataList, String clientId, long version, String srcAddressString, long registerTimestamp, PublishSource publishSource) {
        this.registerId = registerId;
        this.cell = cell;
        this.clientId = clientId;
        this.version = version;
        this.srcAddressString = srcAddressString;
        this.serverDataList = serverDataList == null ? new ArrayList<>(0) : new ArrayList<>(serverDataList);
        this.registerTimestamp = registerTimestamp;
        this.publishSource = publishSource;
    }


    public int getByteSize() {
        if (CollectionUtils.isEmpty(serverDataList)) {
            return 0;
        }
        int bytes = 0;
        for (ServerData serverData : serverDataList) {
            bytes += serverData.byteSize();
        }
        return bytes;
    }


    public int size() {
        int s = StringUtils.sizeof(registerId) + StringUtils.sizeof(cell) + StringUtils.sizeof(srcAddressString) + 40;
        s += getByteSize();
        return s;
    }
}
